<script setup lang="ts">
import dayjs from 'dayjs'

const options = [{
  value: '1',
  label: '男',
}, {
  value: '2',
  label: '女',
}]

const sex = ref('1')

const name = ref()

const isSubmit = ref(false)

const router = useRouter()

const birthdate = ref(new Date('2000-01-01'))
function handleDate(date: Date) {
  birthdate.value = date
}

// 关闭弹窗
function closeModal() {
  isSubmit.value = false
}

const lunarInfo = [
  0x4BD8,
  0x4AE0,
  0xA570,
  0x54D5,
  0xD260,
  0xD950,
  0x5554,
  0x56AF,
  0x9AD0,
  0x55D2,
  0x4AE0,
  0xA5B6,
  0xA4D0,
  0xD250,
  0xD295,
  0xB54F,
  0xD6A0,
  0xADA2,
  0x95B0,
  0x4977,
  0x497F,
  0xA4B0,
  0xB4B5,
  0x6A50,
  0x6D40,
  0xAB54,
  0x2B6F,
  0x9570,
  0x52F2,
  0x4970,
  0x6566,
  0xD4A0,
  0xEA50,
  0x6A95,
  0x5ADF,
  0x2B60,
  0x86E3,
  0x92EF,
  0xC8D7,
  0xC95F,
  0xD4A0,
  0xD8A6,
  0xB55F,
  0x56A0,
  0xA5B4,
  0x25DF,
  0x92D0,
  0xD2B2,
  0xA950,
  0xB557,
  0x6CA0,
  0xB550,
  0x5355,
  0x4DAF,
  0xA5B0,
  0x4573,
  0x52BF,
  0xA9A8,
  0xE950,
  0x6AA0,
  0xAEA6,
  0xAB50,
  0x4B60,
  0xAAE4,
  0xA570,
  0x5260,
  0xF263,
  0xD950,
  0x5B57,
  0x56A0,
  0x96D0,
  0x4DD5,
  0x4AD0,
  0xA4D0,
  0xD4D4,
  0xD250,
  0xD558,
  0xB540,
  0xB6A0,
  0x95A6,
  0x95BF,
  0x49B0,
  0xA974,
  0xA4B0,
  0xB27A,
  0x6A50,
  0x6D40,
  0xAF46,
  0xAB60,
  0x9570,
  0x4AF5,
  0x4970,
  0x64B0,
  0x74A3,
  0xEA50,
  0x6B58,
  0x5AC0,
  0xAB60,
  0x96D5,
  0x92E0,
  0xC960,
  0xD954,
  0xD4A0,
  0xDA50,
  0x7552,
  0x56A0,
  0xABB7,
  0x25D0,
  0x92D0,
  0xCAB5,
  0xA950,
  0xB4A0,
  0xBAA4,
  0xAD50,
  0x55D9,
  0x4BA0,
  0xA5B0,
  0x5176,
  0x52BF,
  0xA930,
  0x7954,
  0x6AA0,
  0xAD50,
  0x5B52,
  0x4B60,
  0xA6E6,
  0xA4E0,
  0xD260,
  0xEA65,
  0xD530,
  0x5AA0,
  0x76A3,
  0x96D0,
  0x4AFB,
  0x4AD0,
  0xA4D0,
  0xD0B6,
  0xD25F,
  0xD520,
  0xDD45,
  0xB5A0,
  0x56D0,
  0x55B2,
  0x49B0,
  0xA577,
  0xA4B0,
  0xAA50,
  0xB255,
  0x6D2F,
  0xADA0,
  0x4B63,
  0x937F,
  0x49F8,
  0x4970,
  0x64B0,
  0x68A6,
  0xEA5F,
  0x6B20,
  0xA6C4,
  0xAAEF,
  0x92E0,
  0xD2E3,
  0xC960,
  0xD557,
  0xD4A0,
  0xDA50,
  0x5D55,
  0x56A0,
  0xA6D0,
  0x55D4,
  0x52D0,
  0xA9B8,
  0xA950,
  0xB4A0,
  0xB6A6,
  0xAD50,
  0x55A0,
  0xABA4,
  0xA5B0,
  0x52B0,
  0xB273,
  0x6930,
  0x7337,
  0x6AA0,
  0xAD50,
  0x4B55,
  0x4B6F,
  0xA570,
  0x54E4,
  0xD260,
  0xE968,
  0xD520,
  0xDAA0,
  0x6AA6,
  0x56DF,
  0x4AE0,
  0xA9D4,
  0xA4D0,
  0xD150,
  0xF252,
  0xD520,
]

const nStr1 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
const nStr2 = ['初', '十', '廿', '卅']
const monthName = ['', '正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二']
const userInfo = useUserInfoState()
async function submitHandle() {
  const userName = name.value
  if (userName == '' || userName == null || userName == undefined) {
    isSubmit.value = true
    return
  }
  const gender = sex.value
  const userBirthdate = dayjs(birthdate.value).format('YYYY-MM-DD HH:mm:ss')
  // console.log(userBirthdate)
  const date1 = userBirthdate.split(' ')[0]
  const date2 = userBirthdate.split(' ')[1]
  const date1Array = date1?.split('-') || []
  const y = Number(date1Array[0] || 0)
  let m = Number(date1Array[1] || 0)
  let d = Number(date1Array[2] || 0)
  console.log('ddd', y, m, d)
  const ys = y
  const ms = m
  const ds = d
  const date2Array = date2?.split(':') || []
  const h = Number(date2Array[0] || 0)
  const i = Number(date2Array[1] || 0)
  // console.log(ys, ms, ds, h, i)
  m = m - 1
  d = d - 1

  let cY, cM, cD, cH
  if (m < 2)
    cY = y - 1900 + 36 - 1
  else cY = y - 1900 + 36
  const term2 = sTerm_d(y, 2)
  if (m == 1 && (d + 1) > term2)
    cY = y - 1900 + 36
  if (m == 1 && (d + 1) == term2 && (h * 60 + i) >= sTerm_hi(y, 2))
    cY = y - 1900 + 36
  const firstNode = sTerm_d(y, m * 2)
  cM = (y - 1900) * 12 + m + 12
  let start_term = (Date.UTC(y, m, d + 1, h, i, 0, 0) - Number(sTerm_s(y, m * 2 - 2))) / 1000
  let start_term1 = wzc(y, m * 2 - 2)
  if (m == 0) {
    start_term = (Date.UTC(y, m, d + 1, h, i, 0, 0) - Number(sTerm_s(y - 1, 22))) / 1000
    start_term1 = wzc(y - 1, 22)
  }
  let end_term = (Number(sTerm_s(y, m * 2)) - Date.UTC(y, m, d + 1, h, i, 0)) / 1000
  let end_term1 = wzc(y, m * 2)
  if ((d + 1) > firstNode || ((d + 1) == firstNode && (h * 60 + i * 1) >= sTerm_hi(y, m * 2))) {
    cM = (y - 1900) * 12 + m + 13
    start_term = (Date.UTC(y, m, d + 1, h, i, 0, 0) - Number(sTerm_s(y, m * 2))) / 1000
    start_term1 = wzc(y, m * 2)
    end_term = (Number(sTerm_s(y, m * 2 + 2)) - Date.UTC(y, m, d + 1, h, i, 0)) / 1000
    end_term1 = wzc(y, m * 2 + 2)
    if (m == 11) {
      end_term = (Number(sTerm_s(y + 1, 0)) - Date.UTC(y, m, d + 1, h, i, 0, 0)) / 1000
      end_term1 = wzc(y + 1, 0)
    }
  }
  if (start_term < 0)
    start_term = 0
  if (end_term < 0)
    end_term = 0
  const dayCyclical = Date.UTC(y, m, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10
  cD = dayCyclical + d
  if (h >= 23)
    cD = dayCyclical + d + 1
  let nh
  if (h == 23 || h == 1 || h == 3 || h == 5 || h == 7 || h == 9 || h == 11 || h == 13 || h == 15 || h == 17 || h == 19 || h == 21) {
    nh = h - 1
    nh = nh + 2
  }
  else {
    nh = h
  }
  const houseCyclical = (Date.UTC(y, m, d + 1, nh, 0, 0, 0) / 3600000 + 25567 * 24) / 2
  cH = houseCyclical

  const lDate = lll(y, m, d, h)

  // console.log('ys', ys)
  // console.log('ms', ms)
  // console.log('ds', ds)
  // console.log('cY', cY)
  // console.log('cM', cM)
  // console.log('cD', cD)
  // console.log('cH', cH)
  // console.log('term1', wzc(y, m * 2))
  // console.log('term2', wzc(y, m * 2 + 1))
  // console.log('start_term', start_term)
  // console.log('end_term', end_term)
  // console.log('start_term1', start_term1)
  // console.log('end_term1', end_term1)
  // console.log('lDate', lDate)
  const data = {
    name: userName,
    gender,
    // datetext: birthdate.value,
    // birthday: date1,
    // hour: h,
    y: ys,
    m: ms,
    d: ds,
    h,
    i,
    cY,
    cM,
    cD,
    cH,
    term1: wzc(y, m * 2),
    term2: wzc(y, m * 2 + 1),
    start_term,
    end_term,
    start_term1,
    end_term1,
    lDate,
    // privacy_protocol: 'on'
  }
  // console.log(data)
  const { data: res } = await useFetchPost('/api/Quming/quming', {
    data,
    type: 6,
    user_id: userInfo.value.id,
  })

  if (res.value.code == 200) {
    // console.log('oid', res.value.data.oid)
    router.push({
      path: '/quming/loading',
      query: { oid: res.value.data.oid, name: userName, sex: gender, birthday: userBirthdate },
    })
  }
}

function lYearDays(y: number) {
  let i; let sum = 348
  for (i = 0x8000; i > 0x8; i >>= 1) sum += (lunarInfo[y - 1900]! & i) ? 1 : 0
  return (sum + leapDays(y))
}

function leapDays(y: number) {
  if (leapMonth(y))
    return ((lunarInfo[y - 1899]! & 0xF) == 0xF ? 30 : 29)
  else return (0)
}

function leapMonth(y: number) {
  const lm = lunarInfo[y - 1900]! & 0xF
  return (lm == 0xF ? 0 : lm)
}

function monthDays(y: number, m: number) {
  return ((lunarInfo[y - 1900]! & (0x10000 >> m)) ? 30 : 29)
}

const year = ref()

const month = ref()

const day = ref()

const isLeap = ref()

function Lunar(objDate: Date) {
  let i; let leap = 0
  let temp = 0
  let offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0, 31)) / 86400000
  if (objDate.getHours() >= 23) {
    offset++
  }
  for (i = 1900; i < 2100 && offset > 0; i++) {
    temp = lYearDays(i)
    offset -= temp
  }
  if (offset < 0) {
    offset += temp
    i--
  }
  year.value = i
  leap = leapMonth(i)
  isLeap.value = false
  for (i = 1; i < 13 && offset > 0; i++) {
    if (leap > 0 && i == (leap + 1) && isLeap.value == false) {
      --i
      isLeap.value = true
      temp = leapDays(year.value)
    }
    else {
      temp = monthDays(year.value, i)
    }
    if (isLeap.value == true && i == (leap + 1))
      isLeap.value = false
    offset -= temp
  }
  if (offset == 0 && leap > 0 && i == leap + 1) {
    if (isLeap.value) {
      isLeap.value = false
    }
    else {
      isLeap.value = true
      --i
    }
  }
  if (offset < 0) {
    offset += temp
    --i
  }
  month.value = i
  day.value = offset + 1
}

function cYear(y: number) {
  let s
  s = nStr1[Math.floor(y / 1000)]
  s += nStr1[Math.floor((y % 1000) / 100)]!
  s += nStr1[Math.floor((y % 100) / 10)]!
  s += nStr1[y % 10]!
  return (s)
}

function cDay(d: number) {
  let s
  switch (d) {
    case 10:
      s = '初十'
      break
    case 20:
      s = '二十'
      break
    case 30:
      s = '三十'
      break
    default:
      s = nStr2[Math.floor(d / 10)]
      s += nStr1[d % 10]!
  }
  return (s)
}

function lll(y: number, m: number, i: number, h: number) {
  const hh = ['00:00-00:59早子', '01:00-01:59丑', '02:00-02:59丑', '03:00-03:59寅', '04:00-04:59寅', '05:00-05:59卯', '06:00-06:59卯', '07:00-07:59辰', '08:00-08:59辰', '09:00-09:59巳', '10:00-10:59巳', '11:00-11:59午', '12:00-12:59午', '13:00-13:59未', '14:00-14:59未', '15:00-15:59申', '16:00-16:59申', '17:00-17:59酉', '18:00-18:59酉', '19:00-19:59戌', '20:00-20:59戌', '21:00-21:59亥', '22:00-22:59亥', '23:00-23:59晚子']
  const sDObj = new Date(y, m, i + 1, h)
  const lDObj = Lunar(sDObj)
  const lY = cYear(year.value)
  const lM = monthName[month.value]
  const lD = cDay(day.value)
  const lL = isLeap.value ? '闰' : ''
  if (h >= 0 && h < 24) {
    var lS = hh[h] as string
  }
  else {
    var lS = '未知'
  }
  const lH = isLeap.value ? '闰' : ''

  return (`${lY}年${lL}${lM}月${lD}日` + ` ${lS}时`)
}

const sTermInfo: number[] = [0, 21198, 42461, 63813, 85308, 106961, 128806, 150834, 173055, 195433, 217965, 240558, 263215, 285853, 308440, 330912, 353245, 375400, 397371, 419149, 440750, 462193, 483513, 504747]

function wzc(year: number, num: number) {
  const objD = new Date((31556956000 * (year - 1882) + sTermInfo[num]! * 60000) + Date.UTC(1882, 0, 5, 18, 0))
  const hh = objD.getUTCHours()
  const mm = objD.getUTCMinutes()
  const ss = objD.getUTCSeconds()
  const s = `${num}/(${objD.getUTCMonth() + 1}月${objD.getUTCDate()}日${hh}:${mm})`
  return (s)
}

function sTerm_d(y: number, n: number) {
  const offDate = new Date((31556956000 * (y - 1882) + sTermInfo[n]! * 60000) + Date.UTC(1882, 0, 5, 18, 0))
  return (offDate.getUTCDate())
}

function sTerm_hi(y: number, n: number) {
  const offDate = new Date((31556956000 * (y - 1882) + sTermInfo[n]! * 60000) + Date.UTC(1882, 0, 5, 18, 0))
  const hi = offDate.getUTCHours() * 60 + offDate.getUTCMinutes()
  return (hi)
}

function sTerm_s(y: number, n: number) {
  const offDate = new Date((31556956000 * (y - 1882) + sTermInfo[n]! * 60000) + Date.UTC(1882, 0, 5, 18, 0))
  return (offDate)
}
function selectSex(n: string) {
  sex.value = n
}
</script>

<template>
  <div class="min-h-screen w-full relative">
    <Header back="/select" />
    <img
      src="/assets/images/quming/qumingye.png"
      alt=""
      class="h-auto w-full object-contain"
    >
    <div class="top-1/2 writing-vertical -translate-y-1/2 transform right-0 fixed z-50">
      <button
        class="text-white px-2 py-1 rounded-l-lg bg-black/60 transition hover:bg-gray-800"
        @click="router.push('orders')"
      >
        查看订单
      </button>
    </div>
    <!-- 性别 -->
    <!-- <div class="absolute w-[90%] mx-auto left-0 right-0 top-[30%] flex justify-around">
        <div class="w-[70px] opacity-0 animate-fade-in-up delay-[200ms]" @click="selectSex('1')">
            <img class="relative"
                src="/assets/images/quming/boy.png"
            />
            <img v-if="sex == '1'" class="absolute top-0 left-0 right-0 mx-auto w-full h-full object-contain"
                src="/assets/images/quming/boy-border.png"
            />
        </div>
        <div class="w-[70px] opacity-0 animate-fade-in-up delay-[200ms]" @click="selectSex('2')">
            <img class="relative"
                src="/assets/images/quming/girl.png"
            />
            <img v-if="sex == '2'" class="absolute top-0 left-0 right-0 mx-auto w-full h-full object-contain"
                src="/assets/images/quming/girl-border.png"
            />
        </div>
    </div>
    <div class="absolute left-0 right-0 mx-auto bottom-[45%] w-[90%] opacity-0 animate-fade-in-up delay-[200ms]">
        <div class="border-2 rounded-lg border-[#9f8257] h-15 flex items-center px-4 bg-[#fef9f0]">
            <span class="font-bold text-xl text-[#7d5B2F]">姓氏：</span>
            <UInput class="text-[#7d5B2F]" size="xl" v-model="name" variant="none" />
        </div>
    </div>
    <div class="absolute left-0 right-0 mx-auto bottom-[35%] w-[90%] opacity-0 animate-fade-in-up delay-[200ms]">
        <div class="border-2 rounded-lg border-[#9f8257] h-15 flex items-center px-4 bg-[#fef9f0]">
            <span class="font-bold text-xl text-[#7d5B2F]">生日：</span>
            <LunarDatePicker @change="handleDate" v-model="birthdate" class="flex-1" />
        </div>
    </div>
    <div class="absolute bottom-45 left-0 right-0 flex justify-center animate-scale">
        <button @click="submitHandle" class="flex items-center justify-center">
            <img src="/assets/images/quming/submit.png" alt="" class="h-15" />
        </button>
    </div>
    <TipModal
      v-model="isSubmit"
      title="提示"
      message="请填写姓名"
      @close="closeModal"
    /> -->
    <div class="w-full top-[18%] absolute">
      <div class="px-4 opacity-0 flex flex-col gap-y-5 delay-[200ms] items-center animate-fade-in-up md:gap-y-6">
        <!-- 性别选择 -->
        <div class="flex gap-8 w-full justify-center">
          <div class="w-[60px] relative md:w-[70px]" @click="selectSex('1')">
            <img class="w-full" src="/assets/images/quming/boy.png">
            <img
              v-if="sex == '1'"
              class="h-full w-full inset-0 absolute animate-pulse object-contain"
              src="/assets/images/quming/boy-border.png"
            >
          </div>
          <div class="w-[60px] relative md:w-[70px]" @click="selectSex('2')">
            <img class="w-full" src="/assets/images/quming/girl.png">
            <img
              v-if="sex == '2'"
              class="h-full w-full inset-0 absolute animate-pulse object-contain"
              src="/assets/images/quming/girl-border.png"
            >
          </div>
        </div>

        <!-- 姓氏输入 -->
        <div class="max-w-[90%] w-full">
          <div class="px-4 border-2 border-[#996600] rounded-lg bg-[#f1e1cb] flex h-12 items-center md:h-15">
            <span class="text-xl text-[#996600] font-bold">姓氏：</span>
            <UInput v-model="name" placeholder="请输入姓氏（1-2个汉字）" :ui="{ placeholder: '!placeholder-[#996600]' }" class="text-[#996600] flex-1 w-[70%]" size="xl" variant="none" />
          </div>
        </div>

        <!-- 生日选择 -->
        <div class="max-w-[90%] w-full">
          <div class="px-4 border-2 border-[#996600] rounded-lg bg-[#f1e1cb] flex h-12 items-center md:h-15">
            <span class="text-xl text-[#996600] font-bold">生日：</span>
            <LunarDatePicker v-model="birthdate" class="flex-1" @change="handleDate" />
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="animate-scale">
          <button @click="submitHandle">
            <img src="/assets/images/quming/submit.png" alt="提交" class="h-12 md:h-15">
          </button>
        </div>
      </div>

      <TipModal
        v-model="isSubmit"
        title="提示"
        message="请填写姓名"
        @close="closeModal"
      />
    </div>
  </div>
</template>

<style scoped>
/* 自定义淡入上升动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 注册Tailwind动画 */
.animate-fade-in-up {
  animation: fadeInUp 0.2s ease-out forwards;
}

/* 定义延迟类 */
.delay-\[200ms\] {
  animation-delay: 200ms;
}

@keyframes scaleAnimation {
  0% {
    transform: scale(0.8);
  }
  50% {
    transform: scale(1); /* 放大到 120% */
  }
  100% {
    transform: scale(0.8); /* 恢复到原始大小 */
  }
}

.animate-scale {
  animation: scaleAnimation 2s ease-in-out infinite; /* 动画时长为 2秒，循环播放 */
}

.writing-vertical {
  writing-mode: vertical-rl;
  text-orientation: upright;
  letter-spacing: 0.1em;
  line-height: 1.4;
}
</style>
